package utils

import (
	"fmt"
	"io/ioutil"
	"net"
	"os/exec"
	"regexp"
	"runtime"
	"strings"
)

func GetCpuId() string {
	print(runtime.GOOS + "\r\n")
	str := ""
	if runtime.GOOS == "linux" {
		cmd := exec.Command("/bin/sh", "-c", `sudo dmidecode -t 4 | grep ID `)
		stdout, err := cmd.StdoutPipe()
		if err != nil {
			fmt.Println("StdoutPipe: " + err.Error())
			str = ""
		}

		stderr, err := cmd.StderrPipe()
		if err != nil {
			fmt.Println("StderrPipe: ", err.Error())
			str = ""
		}

		if err := cmd.Start(); err != nil {
			fmt.Println("Start: ", err.Error())
			str = ""
		}

		bytesErr, err := ioutil.ReadAll(stderr)
		if err != nil {
			fmt.Println("ReadAll stderr: ", err.Error())
			str = ""
		}

		if len(bytesErr) != 0 {
			fmt.Printf("stderr is not nil: %s", bytesErr)
			str = ""
		}

		bytes, err := ioutil.ReadAll(stdout)
		if err != nil {
			fmt.Println("ReadAll stdout: ", err.Error())
			str = ""
		}

		if err := cmd.Wait(); err != nil {
			fmt.Println("Wait: ", err.Error())
			str = ""
		}
		str = string(bytes)
	} else if runtime.GOOS == "windows" {
		cmd := exec.Command("wmic", "cpu", "get", "ProcessorID")
		out, err := cmd.CombinedOutput()
		if err != nil {
			fmt.Println(err)
		}
		fmt.Println(string(out))
		str = string(out)
		//匹配一个或多个空白符的正则表达式
		reg := regexp.MustCompile("\\s+")
		str = reg.ReplaceAllString(str, "")
		str = str[11:]
	}
	str = strings.ReplaceAll(str, " ", "")
	str = strings.Replace(str, "ID:", "", -1)[0:15]
	print("cpuID:", str+"\r\n")
	return str
}

func GetMacAddrs() (macAddresss []string) {
	netInterfaces, err := net.Interfaces()
	if err != nil {
		fmt.Printf("fail to get net interfaces: %v", err)
		return macAddresss
	}

	for _, netInterface := range netInterfaces {
		macAddr := netInterface.HardwareAddr.String()
		if len(macAddr) == 0 {
			continue
		}

		macAddresss = append(macAddresss, macAddr)
	}
	return macAddresss
}
